package polsl.biai.projekt.client;

import com.google.gwt.core.client.JsArray;


import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.base.LatLng;

import com.google.gwt.maps.client.overlays.MarkerOptions;
import com.google.gwt.maps.client.overlays.Marker;
import com.google.gwt.maps.client.services.Geocoder;

import com.google.gwt.maps.client.services.GeocoderGeometry;
import com.google.gwt.maps.client.services.GeocoderRequest;
import com.google.gwt.maps.client.services.GeocoderRequestHandler;
import com.google.gwt.maps.client.services.GeocoderResult;
import com.google.gwt.maps.client.services.GeocoderStatus;


public class CheckCityOnMap {

	
	private MapWidget map;
	Geocoder geocoder;
	
	//marker to show city on map
	private Marker marker;
	
	//if ok == true city exists
	boolean ok = false;
	

	CheckCityOnMap(MapWidget m, Geocoder g) {
		map = m;
		geocoder = g;
		marker = Marker.newInstance(MarkerOptions.newInstance());
	}
	
	public boolean isAddressOk()
	{
		return ok;
	}

	public void showAddress(final String address) {

		
		ok = false;
		
		//creates new GeocoderRequest
		GeocoderRequest request = GeocoderRequest.newInstance();
		
		//sets address
		request.setAddress(address);

		//sends request to the server
		geocoder.geocode(request, new GeocoderRequestHandler() {

			@Override
			public void onCallback(JsArray<GeocoderResult> results,	GeocoderStatus status) {
				if (status == GeocoderStatus.OK) {

					//if Google found city
					if (results.length() > 0) {
						//gets the fittest city
						GeocoderResult result = results.get(0);

						//gets city's location
						GeocoderGeometry gg = result.getGeometry();
						LatLng point = gg.getLocation();
						
						//sets marker to show city on map
						map.setCenter(point);
						marker.setMap(map);
						marker.setPosition(point);
						
						//sets ok true - means city exists
						ok = true;
					}
				}
			}

		});
	}

}
